#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<functional>
#include "Logger.hpp"
#include "InetAddr.hpp"

const static int defaultfd = -1;
using call_back=std::function<void(int sockfd,std::string message,InetAddr addr)>; 
class ChatServer
{
public:
    ChatServer(uint16_t port,call_back cb)
        : _sockfd(defaultfd), _port(port),_cb(cb),_isrunning(false)
    {
    }
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "sock创建失败";
            exit(1);
        }
        LOG(LogLevel::INFO) << "sock创建成功" << _sockfd;
        InetAddr local(_port);
        int n = bind(_sockfd, local.Addr(), local.Len());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind失败" << _sockfd;
            exit(2);
        }
        LOG(LogLevel::FATAL) << "bind成功" << _sockfd;
    }
    void Start()
    {
        _isrunning=true;
        while (_isrunning)
        {
            char buffer[1024];
            buffer[0]=0;
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int n = recvfrom(_sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                buffer[n]=0;
                InetAddr Client(peer);
                std::string message="client to say #";
                message+=buffer;
                LOG(LogLevel::INFO)<<"[ ip:"<<Client.Ip()<<" - port:"<<Client.Port()<<" ] "<<message;
                _cb(_sockfd,message,Client);
            }
        }
        _isrunning=false;
    }
    void Stop()
    {
        _isrunning=false;
    }
    ~ChatServer() {}

private:
    int _sockfd;
    uint16_t _port;
    call_back _cb;
    bool _isrunning;
};